const axios = require("axios");
const fs = require("fs");
const path = require("path");

const type = "pie";
const headers = {
  Accept: "application/json, text/plain, */*",
  "Accept-Encoding": "gzip, deflate, br, zstd",
  "Accept-Language": "zh-CN,zh;q=0.9",
  "Content-Length": "0",
  Origin: "https://www.isqqw.com",
  Priority: "u=1, i",
  Referer: "https://www.isqqw.com/",
  "Sec-Ch-Ua":
    '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
  "Sec-Ch-Ua-Mobile": "?0",
  "Sec-Ch-Ua-Platform": '"Windows"',
  "Sec-Fetch-Dest": "empty",
  "Sec-Fetch-Mode": "cors",
  "Sec-Fetch-Site": "same-site",
  Token:
    "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MjQ4NDY0MTAsInVzZXJuYW1lIjoid29haWNoaXR1ZG91In0.smq6Ky0y154gwnqWqwFi4BZlEgTyZwTK1HH7OrjDZn4",
  "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
};

function getFileNameFromUrl(url) {
  const urlObject = new URL(url);
  const fileName = urlObject.pathname.split("/").pop();
  return fileName;
}

async function downloadImage(url, filePath) {
  const writer = fs.createWriteStream(filePath);
  const response = await axios({
    headers,
    url,
    method: "GET",
    responseType: "stream",
  });

  response.data.pipe(writer);

  return new Promise((resolve, reject) => {
    writer.on("finish", resolve);
    writer.on("error", reject);
  });
}

const baseURL = "https://api.isqqw.com/api/1.1/charts/list";
const params = {
  searchWord: "",
  pageNum: 1,
  pageSize: 36,
  typeCode: type,
  libraryName: "all",
  viewSortStatus: 2,
  sign: "ba777f6183eab1abe439b12d9821130a",
};

const fetchPage = async (pageNum) => {
  try {
    const response = await axios.post(
      baseURL,
      {},
      {
        headers,
        params: { ...params, pageNum },
      }
    );

    const recordsPromises = response.data.data.records.map(async (i) => {
      const url = `https://api.isqqw.com/api/1.1/charts/echartsdetail?id=${i.id}&sign=2524a46d3a79ea55a06cdffab5443cce`;
      try {
        const res = await axios.post(
          url,
          {},
          {
            headers,
          }
        );

        if (i.img) {
          const imgUrl = "https://img.isqqw.com" + i.img;
          const fileName = getFileNameFromUrl(imgUrl);

          if (fileName) {
            console.log(imgUrl);
            const filePath = path.join(__dirname, type, "images", fileName);

            // 创建目录（如果不存在）
            const dir = path.dirname(filePath);
            if (!fs.existsSync(dir)) {
              fs.mkdirSync(dir, { recursive: true });
            }

            await downloadImage(imgUrl, filePath);

            return {
              title: i.title,
              img: `./images/${fileName}`,
              decodedString: res.data.data.code,
            };
          }
        }

        return {
          title: i.title,
          img: null,
          decodedString: res.data.data.code,
        };
      } catch (error) {
        console.error(`请求第 ${pageNum} 页的详细数据失败:`, error);
        return null;
      }
    });

    const records = await Promise.all(recordsPromises);
    return records.filter((record) => record !== null);
  } catch (error) {
    console.error(`请求第 ${pageNum} 页失败:`, error);
    return [];
  }
};

const fetchAllPages = async () => {
  let allRecords = [];

  for (let i = 1; i <= 25; i++) {
    const records = await fetchPage(i);
    if (records.img) {
      allRecords = allRecords.concat(records);
    }
  }

  // 将数据写入到 JS 文件
  const content = `const data = ${JSON.stringify(
    allRecords,
    null,
    2
  )};\nmodule.exports = data;`;
  fs.writeFileSync(path.join(__dirname, type, "data.js"), content, "utf8");
  console.log("数据已写入到 data.js 文件");
};

fetchAllPages();
